var createError = require('http-errors');
// const multer = require('multer')  // l
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

// l
const multer = require('multer')

const app = express()
const { mongoose } = require('./utils/db')

const { enter } = require('./dao/enterDao')
const { queryLogin } = require('./dao/LoginDao')
const { photos, upstudents, queryRoom } = require('./dao/personDao')
const { add } = require('./dao/AddDao')

// 张胖胖
const StudentDao = require('./dao/StudentDao'); // 连接 StudentDao
const TypeDao = require('./dao/TypeDao'); // 连接 TypeDao
const TestDao = require('./dao/TestDao'); // 连接 TestDao
const TestedDao = require('./dao/TestedDao'); // 连接 TestedDao

// 张胖胖
// l

const db = require('./utils/DB')
const ErrorDao = require('./dao/ErrorDao')
const CollectDao = require('./dao/CollectDao')
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
//静态文件托管：一定要放在这里，静态资源才能通过网址访问到
app.use(express.static(path.resolve('public')));
// 文件上传配置
app.use(multer({ dest: '/tmp/' }).array('userphoto', 1));

// l
// 引入Room集合
const { Room } = require('./modle/lsh_Room')
const { Exercises } = require('./modle/lsh_exercises')
const { Student } = require("./modle/Student")
const jwt = require('jsonwebtoken');
const expressJWT = require('express-jwt')
const bodyParser = require('body-parser')

const PRIVITEKEY = "exammanager"
// app.use(bodyParser.urlencoded({extended:false}))


// app.use(bodyParser.urlencoded({ extended: false }))
// l



app.use("*", function (req, res, next) {
  //1.允许任意域名访问
  res.setHeader('Access-Control-Allow-Origin', '*');
  //2.允许任意的请求方式来访问，默认只认：GET、POST、PUT、DELETE
  res.setHeader('Access-Control-Allow-Methods', '*');
  //3.允许任意的HTTP请求头
  res.setHeader('Access-Control-Allow-Headers', '*');
  next();
})

// app.get('/',function (req,res) { 
//   res.send('success')
//  })

//3.express-jwt验证token是否正确(此方法写在静态资源加载之后)
// app.use(expressJWT({
//     secret: PRIVITEKEY,
//     algorithms: ['HS256']
// }).unless({
// 　 path: ['/login']  //白名单,表示不会去验证
// }));

/**
 * 查找错题集
 * http://localhost:3000/findError
 */
app.get('/findError', function (req, res) {
  ErrorDao.findError({
    studentId: db.mongoose.Types.ObjectId(req.query.studentId)
  }, function (data) {
    res.send(data);
  })
})

/**
 * 查找收藏
 * http://localhost:3000/findCollect
 */
app.get('/findCollect', function (req, res) {
  CollectDao.findCollect({
    studentId: db.mongoose.Types.ObjectId(req.query.studentId)
  }, function (data) {
    res.send(data)
  })
})
/**
 * 添加收藏
 * http://localhost:3000/addCollect
 */
app.post('/addCollect', function (req, res) {
  var studentId = db.mongoose.Types.ObjectId(req.body.studentId)
  // var nba=req.body.nba
  console.log('学生id :' + studentId);
  // console.log(nba);
  var exerciseId = db.mongoose.Types.ObjectId(req.body.exerciseId)
  CollectDao.addCollect({
    studentId,
    exerciseId
  }, function (data) {
    console.log(data)
  })
})
/**
 * 取消收藏
 * http://localhost:3000/addCollect
 */
app.post('/delCollect', function (req, res) {
  var studentId = db.mongoose.Types.ObjectId(req.body.studentId)
  var exerciseId = db.mongoose.Types.ObjectId(req.body.exerciseId)
  console.log('学生id :' + studentId);
  CollectDao.delCollect({
    studentId,
    exerciseId
  }, function (data) {
    console.log(data);
  })
})



// 登录 --- 接收数据
app.post('/enter', function (req, res) {
  enter(req, res)
})


// 注册 --- 加入数据库
app.post('/login', function (req, res) {
  queryLogin([req.body.text_word, req.body.password,], function (data) {
    enter(req, res)
  })
})

// let name = null;
// 头像加入
app.post('/add', function (req, res) {
  let phone = req.body.phone;
  let sex = req.body.sex;
  let my_name = req.body.name;

  // 图片加入
  let name = photos(req, res)
  // 数据库加入
  console.log('图片' + name);
  upstudents(phone, name, sex, my_name)

})
// 查询
app.get('/get', function (req, res) {
  console.log('111');
  queryRoom({ phone: req.query.phone }, function (data) {
    let qqq = null;
    for (let i = 0; i < data.length; i++) {
      // console.log(data[i]._doc);
      qqq = data[i]._doc
    }
    res.send(qqq)
  })
})



// 添加
// function add(tg, xx, zqda, jx, fs, zsd) {
//   Exercises.create({		// creat：创建
//     topics: tg,
//     options: xx,
//     answer: parseInt(zqda),
//     analysis: jx,
//     score: parseFloat(fs),
//     pointId: mongoose.Types.ObjectId(zsd),
//     // 分数与所属知识点未写

//   }, function (err, data) {
//     if (err) {
//       console.log(err);
//     }
//     // console.log(data);
//   })
// }
// 问题存储
app.post('/my_add', function (req, res) {
  let tg = req.body.tg
  let xx = req.body.xx
  let zqda = req.body.zqda
  let jx = req.body.jx
  let fs = req.body.fs
  let zsd = req.body.zsd
  add(tg, xx, zqda, jx, fs, zsd)
})


// 张胖胖


// 主页。查询所有 type 存上 type='正式考试' 的id号，给下个页面使用
app.get('/type/list', function (req, res) {
  // res.send('succcess')
  TypeDao.queryTypes(function (arr) {
    res.send(arr)
  });
})


// 正式考试页。通过 userId 获取用户信息
app.post('/nowUser', function (req, res) {
  var userId = req.body.userId;
  StudentDao.queryNowUserByUserId(userId, function (arr) {
    res.send(arr)
  });
})
// 正式考试页。通过上个页面存的 nowType 先获取所有 对应的考试题
app.post('/nowType/test/list', function (req, res) {
  var nowTypeId = req.body.nowTypeId;
  TestDao.queryTestsByNowTypeId(nowTypeId, function (arr) {
    res.send(arr)
  });
})
// 正式考试页。通过 userId 找出 tested 里面的 所有 studentId = userid 的，testId
app.post('/tested/list', function (req, res) {
  var userId = req.body.userId;
  TestedDao.queryTestedIdByUserId(userId, function (arr) {
    res.send(arr)
  });
})

// 张胖胖

//zxd

app.get("/find/list", (req, res) => {
  Exercises.find(function (err, data) {
    res.send(data);
  });
})
app.get("/result/list", (req, res) => {
  Exercises.find(function (err, data) {
    res.send(data);
  });
});
app.get("/message/list", (req, res) => {
  Student.find(data => {
    console.log(data);
    res.send(data);
  })
})
// l


// 测试
app.get('/lsh_exer', (req, res) => {
  Exercises.find(function (err, data) {
    res.send(data)
  })
})




// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;